import React from 'react'
import { Icon } from 'antd'
import { connect } from 'dva'
import Dialog, { destroyFns } from './Dialog';
import modal, { drawer, DrawerDialog, ConfirmDialog, ModalDialog } from './modal'

const confirm = (config) => {
	return modal(ConfirmDialog, config)
}

Dialog.info = function(props) {
  const config = {
    type: 'info',
    icon: <Icon type="info-circle" />,
    okCancel: false,
    ...props,
  };
  return confirm(config);
};

Dialog.success = function(props) {
  const config = {
    type: 'success',
    icon: <Icon type="check-circle" />,
    okCancel: false,
    ...props,
  };
  return confirm(config);
};

Dialog.error = function(props) {
  const config = {
    type: 'error',
    icon: <Icon type="close-circle" />,
    okCancel: false,
    ...props,
  };
  return confirm(config);
};

Dialog.alert = (content) => {
  return Dialog.error({
    title: '提示信息',
    content
  })
}

Dialog.warning = Dialog.warn = function(props) {
  const config = {
    type: 'warning',
    icon: <Icon type="exclamation-circle" />,
    okCancel: false,
    ...props,
  };
  return confirm(config);
};

Dialog.confirm = function(props) {
  const config = {
    type: 'confirm',
    okCancel: true,
    ...props,
  };
  return confirm(config);
};

Dialog.destroyAll = function() {
  while (destroyFns.length) {
    const close = destroyFns.pop();
    if (close) {
      close();
    }
  }
};

Dialog.open = function(props) {
  const {
      connect: mapStateToProps,
      ...config
    } = props
  return modal(connect(mapStateToProps)(ModalDialog), config);
}

Dialog.drawer = function(props) {
	const {
      connect: mapStateToProps,
      ...config
    } = props
  const api = drawer(connect(mapStateToProps)(DrawerDialog), config);
  api.update({
    visible: true
  })
	return api;
}

// 解决 父级组件 调用子组件方法时，由于子组件有使用高阶组件时，无法通过ref直接拿到子组件的引用
export const withRef = WrappedComponent => {
  return class WithRef extends React.Component {
    render() {
      const props = {
        ...this.props,
      };
      // 在这里把getInstance赋值给ref，
      // 传给`WrappedComponent`，这样就getInstance能获取到`WrappedComponent`实例
      props.ref = (node) => {
          this.props.getInstance && this.props.getInstance(node);
          this.props.ref && this.props.ref(node);
      }
      return (
        <WrappedComponent {...props} />
      );
    }
  }
}

export default Dialog